<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预算管理 - 记账助手</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            color: #2d3748;
        }
        
        /* 新增样式 - 预算周期选择器 */
        .period-selector {
            display: flex;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            padding: 4px;
            margin-bottom: 16px;
        }
        
        .period-btn {
            flex: 1;
            padding: 8px 12px;
            border: none;
            background: transparent;
            color: white;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .period-btn.active {
            background: rgba(255, 255, 255, 0.3);
            font-weight: 600;
        }
        
        /* 智能建议卡片 */
        .smart-suggestions {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            color: white;
            box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .suggestion-item {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.15);
            transition: all 0.3s ease;
        }
        
        .suggestion-item:last-child {
            border-bottom: none;
        }
        
        .suggestion-item:hover {
            padding-left: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            margin: 0 -8px;
        }
        
        .suggestion-icon {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.25);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .suggestion-content {
            flex: 1;
        }
        
        .suggestion-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .suggestion-desc {
            font-size: 12px;
            opacity: 0.8;
        }
        
        .suggestion-action {
            background: rgba(255, 255, 255, 0.25);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }
        
        .suggestion-action:hover {
            background: rgba(255, 255, 255, 0.35);
            transform: translateY(-1px);
        }
        
        /* 预算模板 */
        .budget-templates {
            background: white;
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }
        
        .template-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 12px;
            margin-top: 16px;
        }
        
        .template-card {
            border: 2px solid #e9ecef;
            border-radius: 16px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
        }
        
        .template-card:hover {
            border-color: #667eea;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
        }
        
        .template-card.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        
        .template-icon {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .template-name {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .template-desc {
            font-size: 12px;
            color: #6c757d;
        }
        
        /* 预算分析 */
        .budget-analysis {
            background: white;
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }
        
        .analysis-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
            margin-top: 16px;
        }
        
        .analysis-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 16px;
            padding: 20px;
            border: 1px solid rgba(255, 255, 255, 0.6);
            transition: all 0.3s ease;
        }
        
        .analysis-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        .analysis-title {
            font-size: 14px;
            color: #6c757d;
            margin-bottom: 8px;
        }
        
        .analysis-value {
            font-size: 20px;
            font-weight: 600;
            color: #2d3748;
        }
        
        .analysis-trend {
            font-size: 12px;
            margin-top: 4px;
        }
        
        .trend-up {
            color: #dc3545;
        }
        
        .trend-down {
            color: #28a745;
        }
        
        /* 可展开的分类卡片 */
        .category-item {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 12px;
            margin-bottom: 8px;
        }
        
        .category-item:hover {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            transform: translateX(4px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .category-item.expanded {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .category-details {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #e9ecef;
            display: none;
        }
        
        .category-details.show {
            display: block;
        }
        
        .detail-chart {
            height: 120px;
            margin-bottom: 16px;
        }
        
        .recent-expenses {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .expense-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .expense-item:last-child {
            border-bottom: none;
        }
        
        /* 预算调整历史 */
        .adjustment-history {
            background: white;
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }
        
        .history-item {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px 0;
            border-bottom: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .history-item:last-child {
            border-bottom: none;
        }
        
        .history-item:hover {
            background: #f8f9fa;
            border-radius: 12px;
            margin: 0 -12px;
            padding-left: 24px;
            padding-right: 24px;
        }
        
        .history-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            border: 1px solid rgba(255, 255, 255, 0.6);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .history-content {
            flex: 1;
        }
        
        .history-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 2px;
        }
        
        .history-time {
            font-size: 12px;
            color: #6c757d;
        }
        
        .history-amount {
            font-size: 14px;
            font-weight: 600;
        }
        
        /* 预算转移功能 */
        .transfer-section {
            background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
            border: 1px solid #ffeaa7;
            border-radius: 16px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 4px 15px rgba(255, 234, 167, 0.3);
        }
        
        .transfer-title {
            font-size: 14px;
            font-weight: 600;
            color: #856404;
            margin-bottom: 12px;
        }
        
        .transfer-controls {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        
        .transfer-input {
            flex: 1;
            padding: 10px 16px;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            font-size: 14px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
        }
        
        .transfer-input:focus {
            outline: none;
            border-color: #ffc107;
            box-shadow: 0 0 0 3px rgba(255, 193, 7, 0.2);
        }
        
        .transfer-btn {
            background: linear-gradient(135deg, #ffc107 0%, #ffb300 100%);
            border: none;
            color: #856404;
            padding: 10px 20px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
        }
        
        .transfer-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4);
        }
        
        /* 响应式优化 */
        @media (max-width: 768px) {
            .budget-container {
                padding: 16px;
            }
            
            .analysis-grid {
                grid-template-columns: 1fr;
                gap: 12px;
            }
            
            .template-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 8px;
            }
            
            .budget-overview,
            .smart-suggestions,
            .budget-templates,
            .budget-analysis,
            .budget-categories,
            .adjustment-history {
                padding: 20px;
                margin-bottom: 20px;
            }
            
            .section-title {
                font-size: 18px;
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }
            
            .budget-stats {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }
            
            .month-selector {
                margin-right: 0;
                margin-bottom: 8px;
            }
        }
        
        @media (max-width: 480px) {
            .budget-header {
                padding: 20px 16px;
            }
            
            .budget-title {
                font-size: 18px;
            }
            
            .template-grid {
                grid-template-columns: 1fr;
            }
            
            .budget-stats {
                grid-template-columns: 1fr;
            }
            
            .period-selector {
                flex-direction: column;
                gap: 4px;
            }
            
            .period-btn {
                padding: 12px;
                font-size: 16px;
            }
        }
        
        .budget-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 24px 20px;
            position: relative;
            box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
        }
        
        .back-btn {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .budget-title {
            text-align: center;
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        
        .budget-container {
            max-width: 900px;
            margin: 0 auto;
            padding: 24px 20px;
        }
        
        .budget-overview {
            background: white;
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }
        
        .budget-progress {
            margin: 20px 0;
        }
        
        .progress-label {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .progress-bar-container {
            height: 12px;
            background: #e9ecef;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .progress-bar {
            height: 100%;
            border-radius: 8px;
            transition: width 0.3s ease;
            position: relative;
        }
        
        .progress-bar::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 50%;
            background: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), transparent);
            border-radius: 8px 8px 0 0;
        }
        
        .progress-normal {
            background: #4CAF50;
        }
        
        .progress-warning {
            background: #FFC107;
        }
        
        .progress-danger {
            background: #dc3545;
        }
        
        .budget-stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin-top: 20px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 20px;
            border-radius: 16px;
            text-align: center;
            border: 1px solid rgba(255, 255, 255, 0.6);
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        .stat-label {
            font-size: 14px;
            color: #6c757d;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 20px;
            font-weight: 600;
            color: #2d3748;
        }
        
        .budget-categories {
            background: white;
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 28px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }
        
        .category-item {
            padding: 16px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .category-item:last-child {
            border-bottom: none;
        }
        
        .category-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        
        .category-name {
            font-size: 16px;
            font-weight: 500;
            color: #2d3748;
        }
        
        .category-amount {
            font-size: 16px;
            font-weight: 600;
        }
        
        .section-title {
            font-size: 20px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            letter-spacing: -0.5px;
        }
        
        .btn-add {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn-add:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px 20px 0 0;
            border: none;
            padding: 24px;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }
        
        .modal-body {
            padding: 28px;
        }
        
        .form-label {
            font-size: 15px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 10px;
            letter-spacing: -0.2px;
        }
        
        .form-control {
            border-radius: 12px;
            border: 2px solid #e2e8f0;
            padding: 12px 18px;
            font-size: 15px;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
            background: white;
            transform: translateY(-1px);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 12px 28px;
            border-radius: 12px;
            font-weight: 600;
            font-size: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-outline-secondary {
            border: 2px solid #e2e8f0;
            color: #4a5568;
            padding: 12px 28px;
            border-radius: 12px;
            font-weight: 600;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        
        .btn-outline-secondary:hover {
            background: #f8f9fa;
            border-color: #cbd5e0;
            transform: translateY(-1px);
        }
        
        .chart-container {
            margin-top: 20px;
            height: 200px;
        }
        
        /* 添加滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        
        /* 加载动画 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .budget-overview,
        .smart-suggestions,
        .budget-templates,
        .budget-analysis,
        .budget-categories {
            animation: fadeInUp 0.6s ease-out;
        }
        
        .smart-suggestions {
            animation-delay: 0.1s;
        }
        
        .budget-templates {
            animation-delay: 0.2s;
        }
        
        .budget-analysis {
            animation-delay: 0.3s;
        }
        
        .budget-overview {
            animation-delay: 0.4s;
        }
        
        .budget-categories {
            animation-delay: 0.5s;
        }
        
        .month-selector {
            display: flex;
            align-items: center;
            gap: 12px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 8px 16px;
            border-radius: 12px;
            margin-right: 12px;
            border: 1px solid rgba(255, 255, 255, 0.6);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .month-nav {
            font-size: 20px;
            line-height: 1;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .month-nav:hover {
            color: #667eea !important;
            background: rgba(102, 126, 234, 0.1);
            transform: scale(1.1);
        }
        
        #currentMonth {
            font-size: 15px;
            font-weight: 600;
            color: #2d3748;
            min-width: 100px;
            text-align: center;
            letter-spacing: -0.3px;
        }
        
        .year-selector {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            padding: 10px;
            font-size: 18px;
            font-weight: 600;
        }
        
        .month-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            padding: 10px;
        }
        
        .month-btn {
            padding: 15px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
        }
        
        .month-btn:hover {
            border-color: #667eea;
            background: #f8f9fa;
        }
        
        .month-btn.current {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .month-btn.selected {
            background: rgba(102, 126, 234, 0.1);
            border-color: #667eea;
            color: #667eea;
        }
        
        .month-name {
            font-weight: 500;
        }
        
        .month-info {
            font-size: 12px;
            opacity: 0.7;
        }
        
        #currentMonth {
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        
        #currentMonth:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        
        /* 增强的按钮样式 */
        .btn-close {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            width: 32px;
            height: 32px;
            opacity: 1;
            transition: all 0.3s ease;
        }
        
        .btn-close:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }
        
        /* 增强的进度条动画 */
        .progress-bar {
            background-image: linear-gradient(
                45deg,
                rgba(255, 255, 255, 0.15) 25%,
                transparent 25%,
                transparent 50%,
                rgba(255, 255, 255, 0.15) 50%,
                rgba(255, 255, 255, 0.15) 75%,
                transparent 75%,
                transparent
            );
            background-size: 1rem 1rem;
            animation: progress-bar-stripes 1s linear infinite;
        }
        
        @keyframes progress-bar-stripes {
            0% {
                background-position-x: 1rem;
            }
        }
        
        /* 增强的卡片阴影效果 */
        .budget-overview:hover,
        .budget-templates:hover,
        .budget-analysis:hover,
        .budget-categories:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body>
    <div class="budget-header">
        <button class="back-btn" onclick="history.back()">‹</button>
        <h1 class="budget-title">预算管理</h1>
        
        <!-- 预算周期选择器 -->
        <div class="period-selector">
            <button class="period-btn active" data-period="monthly" onclick="switchPeriod('monthly')">月度</button>
            <button class="period-btn" data-period="quarterly" onclick="switchPeriod('quarterly')">季度</button>
            <button class="period-btn" data-period="yearly" onclick="switchPeriod('yearly')">年度</button>
        </div>
    </div>
    
    <div class="budget-container">
        <!-- 智能建议 -->
        <div class="smart-suggestions" id="smartSuggestions">
            <div class="section-title" style="color: white; margin-bottom: 16px;">
                💡 智能建议
            </div>
            <div id="suggestionsList">
                <!-- 建议项将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <!-- 预算模板 -->
        <div class="budget-templates" id="budgetTemplates" style="display: none;">
            <div class="section-title">
                📋 预算模板
                <button class="btn-add" onclick="toggleTemplates()">收起</button>
            </div>
            <div class="template-grid" id="templateGrid">
                <!-- 模板将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <!-- 预算分析 -->
        <div class="budget-analysis">
            <div class="section-title">
                📊 预算分析
            </div>
            <div class="analysis-grid" id="analysisGrid">
                <!-- 分析数据将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <!-- 总预算概览 -->
        <div class="budget-overview">
            <div class="section-title">
                本月总预算
                <div class="d-flex align-items-center gap-2">
                    <div class="month-selector">
                        <button class="btn btn-link text-dark p-0 month-nav" onclick="changeMonth(-1)">‹</button>
                        <span id="currentMonth">2024年5月</span>
                        <button class="btn btn-link text-dark p-0 month-nav" onclick="changeMonth(1)">›</button>
                    </div>
                    <button class="btn-add" onclick="showSetBudgetModal('total')">设置预算</button>
                </div>
            </div>
            
            <div class="budget-progress">
                <div class="progress-label">
                    <span>已使用：¥3,500 / ¥5,000</span>
                    <span>剩余：¥1,500</span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar progress-warning" style="width: 70%"></div>
                </div>
            </div>
            
            <div class="budget-stats">
                <div class="stat-card">
                    <div class="stat-label">预算使用率</div>
                    <div class="stat-value">70%</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">日均支出</div>
                    <div class="stat-value">¥116</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">剩余天数</div>
                    <div class="stat-value">13天</div>
                </div>
            </div>
            
            <div class="chart-container">
                <canvas id="budgetTrendChart"></canvas>
            </div>
        </div>
        
        <!-- 分类预算 -->
        <div class="budget-categories">
            <div class="section-title">
                分类预算
                <button class="btn-add" onclick="showSetBudgetModal('category')">添加分类预算</button>
            </div>
            
            <!-- 分类预算项将通过JavaScript动态生成，支持展开详情 -->
        </div>
    </div>
    
    <!-- 设置预算弹窗 -->
    <div class="modal fade" id="setBudgetModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">设置预算</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="budgetForm">
                        <div class="mb-3" id="categorySelectContainer" style="display: none;">
                            <label class="form-label">选择分类层级</label>
                            <select class="form-control mb-2" id="categoryLevel" onchange="handleCategoryLevelChange()">
                                <option value="primary">一级分类</option>
                                <option value="secondary">二级分类</option>
                            </select>
                            
                            <label class="form-label">一级分类</label>
                            <select class="form-control mb-2" id="primaryCategory" onchange="handlePrimaryCategoryChange()">
                                <option value="">请选择一级分类</option>
                                <option value="food">餐饮</option>
                                <option value="transport">交通</option>
                                <option value="shopping">购物</option>
                                <option value="entertainment">娱乐</option>
                                <option value="medical">医疗</option>
                            </select>
                            
                            <div id="secondaryCategoryContainer" style="display: none;">
                                <label class="form-label">二级分类</label>
                                <select class="form-control" id="secondaryCategory">
                                    <!-- 二级分类选项将通过 JavaScript 动态加载 -->
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">预算金额</label>
                            <input type="number" class="form-control" id="budgetAmount" placeholder="请输入预算金额">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">预算周期</label>
                            <select class="form-control" id="budgetPeriod">
                                <option value="monthly">每月</option>
                                <option value="quarterly">每季度</option>
                                <option value="yearly">每年</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">智能建议</label>
                            <div class="smart-suggestion-card" id="modalSuggestion" style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 12px; display: flex; justify-content: space-between; align-items: center;">
                                <div class="suggestion-text" style="font-size: 14px; color: #495057;">基于您的历史消费，建议设置 ¥1,800</div>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="applySuggestion()">采用建议</button>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">提醒设置</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="warningCheck">
                                <label class="form-check-label" for="warningCheck">
                                    预算使用超过80%时提醒
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveBudget()">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 月份选择器弹窗 -->
    <div class="modal fade" id="monthPickerModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">选择月份</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="year-selector mb-3">
                        <button class="btn btn-link text-dark p-0" onclick="changeYear(-1)">‹</button>
                        <span id="yearDisplay">2024年</span>
                        <button class="btn btn-link text-dark p-0" onclick="changeYear(1)">›</button>
                    </div>
                    <div class="month-grid" id="monthGrid">
                        <!-- 月份将通过 JavaScript 动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 预算调整历史模态框 -->
    <div class="modal fade" id="adjustmentHistoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">预算调整历史</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="adjustmentHistoryList">
                        <!-- 调整历史将通过JavaScript动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 预算转移模态框 -->
    <div class="modal fade" id="budgetTransferModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">预算转移</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">从类别</label>
                        <select class="form-control" id="transferFromCategory">
                            <!-- 选项将通过JavaScript动态生成 -->
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">到类别</label>
                        <select class="form-control" id="transferToCategory">
                            <!-- 选项将通过JavaScript动态生成 -->
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">转移金额</label>
                        <input type="number" class="form-control" id="transferAmount" placeholder="请输入转移金额">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">转移原因</label>
                        <textarea class="form-control" id="transferReason" rows="3" placeholder="请输入转移原因（可选）"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="confirmTransfer()">确认转移</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let currentPeriod = 'monthly';
        let budgetData = {
            monthly: {},
            quarterly: {},
            yearly: {}
        };
        let adjustmentHistory = [];
        let budgetTemplates = [
            {
                name: '学生模板',
                description: '适合学生的基础预算',
                icon: '🎓',
                categories: {
                    '餐饮': 800,
                    '交通': 200,
                    '娱乐': 300,
                    '学习': 400
                }
            },
            {
                name: '上班族模板',
                description: '适合上班族的标准预算',
                icon: '💼',
                categories: {
                    '餐饮': 1500,
                    '交通': 800,
                    '购物': 1000,
                    '娱乐': 600,
                    '其他': 500
                }
            },
            {
                name: '家庭模板',
                description: '适合家庭的综合预算',
                icon: '👨‍👩‍👧‍👦',
                categories: {
                    '餐饮': 3000,
                    '交通': 1200,
                    '购物': 2000,
                    '教育': 1500,
                    '医疗': 800,
                    '其他': 1000
                }
            }
        ];
        
        // 智能建议数据
        let smartSuggestions = [
            {
                type: 'overspend',
                title: '餐饮支出偏高',
                description: '本月餐饮支出已超预算20%，建议适当控制',
                icon: '⚠️',
                action: '查看详情'
            },
            {
                type: 'save',
                title: '交通费用节省',
                description: '相比上月节省了15%的交通费用',
                icon: '💰',
                action: '继续保持'
            },
            {
                type: 'adjust',
                title: '预算调整建议',
                description: '建议将娱乐预算转移200元到餐饮',
                icon: '🔄',
                action: '一键调整'
            }
        ];
        
        // 初始化预算趋势图表
        const ctx = document.getElementById('budgetTrendChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
                datasets: [{
                    label: '预算使用',
                    data: [0, 1200, 2100, 2800, 3500],
                    borderColor: '#667eea',
                    tension: 0.4,
                    fill: false
                }, {
                    label: '预算线',
                    data: [0, 833, 1666, 2500, 3333, 4166, 5000],
                    borderColor: '#e2e8f0',
                    borderDash: [5, 5],
                    tension: 0,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '¥' + value
                        }
                    }
                }
            }
        });
        
        // 切换预算周期
        function switchPeriod(period) {
            currentPeriod = period;
            
            // 更新按钮状态
            document.querySelectorAll('.period-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`[data-period="${period}"]`).classList.add('active');
            
            // 更新显示
            updateBudgetDisplay();
            updateSmartSuggestions();
            updateAnalysisData();
        }
        
        // 更新智能建议
        function updateSmartSuggestions() {
            const suggestionsList = document.getElementById('suggestionsList');
            suggestionsList.innerHTML = '';
            
            smartSuggestions.forEach(suggestion => {
                const suggestionItem = document.createElement('div');
                suggestionItem.className = 'suggestion-item';
                suggestionItem.innerHTML = `
                    <div class="suggestion-icon">${suggestion.icon}</div>
                    <div class="suggestion-content">
                        <div class="suggestion-title">${suggestion.title}</div>
                        <div class="suggestion-desc">${suggestion.description}</div>
                    </div>
                    <button class="suggestion-action" onclick="handleSuggestionAction('${suggestion.type}')">${suggestion.action}</button>
                `;
                suggestionsList.appendChild(suggestionItem);
            });
        }
        
        // 处理建议操作
        function handleSuggestionAction(type) {
            switch(type) {
                case 'overspend':
                    // 显示详细支出分析
                    showExpenseDetails();
                    break;
                case 'save':
                    // 显示节省统计
                    showSavingsStats();
                    break;
                case 'adjust':
                    // 显示预算转移界面
                    showBudgetTransferModal();
                    break;
            }
        }
        
        // 显示预算模板
        function toggleTemplates() {
            const templatesDiv = document.getElementById('budgetTemplates');
            const isVisible = templatesDiv.style.display !== 'none';
            
            if (isVisible) {
                templatesDiv.style.display = 'none';
            } else {
                templatesDiv.style.display = 'block';
                loadBudgetTemplates();
            }
        }
        
        // 加载预算模板
        function loadBudgetTemplates() {
            const templateGrid = document.getElementById('templateGrid');
            templateGrid.innerHTML = '';
            
            budgetTemplates.forEach((template, index) => {
                const templateCard = document.createElement('div');
                templateCard.className = 'template-card';
                templateCard.innerHTML = `
                    <div class="template-icon">${template.icon}</div>
                    <div class="template-name">${template.name}</div>
                    <div class="template-desc">${template.description}</div>
                `;
                templateCard.onclick = () => selectTemplate(index);
                templateGrid.appendChild(templateCard);
            });
        }
        
        // 选择模板
        function selectTemplate(index) {
            // 移除之前的选中状态
            document.querySelectorAll('.template-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // 添加选中状态
            document.querySelectorAll('.template-card')[index].classList.add('selected');
            
            // 应用模板
            const template = budgetTemplates[index];
            applyBudgetTemplate(template);
        }
        
        // 应用预算模板
        function applyBudgetTemplate(template) {
            const yearMonth = formatYearMonth(currentDate);
            let budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
            
            // 为每个分类创建预算
            Object.entries(template.categories).forEach(([categoryName, amount]) => {
                const budgetData = {
                    amount: amount,
                    period: currentPeriod,
                    warning: true,
                    yearMonth: yearMonth,
                    type: 'primary',
                    primaryCategory: getCategoryKeyByName(categoryName),
                    secondaryCategory: null,
                    createdAt: new Date().toISOString(),
                    source: 'template'
                };
                
                // 检查是否已存在相同的预算
                const existingIndex = budgets.findIndex(b => 
                    b.yearMonth === budgetData.yearMonth &&
                    b.type === budgetData.type &&
                    b.primaryCategory === budgetData.primaryCategory
                );
                
                if (existingIndex !== -1) {
                    budgets[existingIndex] = budgetData;
                } else {
                    budgets.push(budgetData);
                }
            });
            
            localStorage.setItem('budgets', JSON.stringify(budgets));
            updateBudgetDisplay();
            showAlert(`已应用${template.name}，共设置${Object.keys(template.categories).length}个分类预算`);
        }
        
        // 根据分类名称获取分类键
        function getCategoryKeyByName(name) {
            const categoryMap = {
                '餐饮': 'food',
                '交通': 'transport',
                '购物': 'shopping',
                '娱乐': 'entertainment',
                '医疗': 'medical',
                '学习': 'education',
                '教育': 'education',
                '其他': 'other'
            };
            return categoryMap[name] || 'other';
        }
        
        // 更新分析数据
        function updateAnalysisData() {
            const analysisGrid = document.getElementById('analysisGrid');
            
            // 模拟分析数据
            const analysisData = [
                {
                    title: '本月节省',
                    value: '¥320',
                    trend: '↓ 12%',
                    trendClass: 'trend-down'
                },
                {
                    title: '超支风险',
                    value: '中等',
                    trend: '↑ 5%',
                    trendClass: 'trend-up'
                },
                {
                    title: '预算执行率',
                    value: '85%',
                    trend: '↑ 8%',
                    trendClass: 'trend-up'
                },
                {
                    title: '平均日支出',
                    value: '¥156',
                    trend: '↓ 3%',
                    trendClass: 'trend-down'
                }
            ];
            
            analysisGrid.innerHTML = '';
            analysisData.forEach(data => {
                const analysisCard = document.createElement('div');
                analysisCard.className = 'analysis-card';
                analysisCard.innerHTML = `
                    <div class="analysis-title">${data.title}</div>
                    <div class="analysis-value">${data.value}</div>
                    <div class="analysis-trend ${data.trendClass}">${data.trend}</div>
                `;
                analysisGrid.appendChild(analysisCard);
            });
        }
        
        // 显示预算转移模态框
        function showBudgetTransferModal() {
            const modal = new bootstrap.Modal(document.getElementById('budgetTransferModal'));
            loadTransferCategories();
            modal.show();
        }
        
        // 加载转移分类选项
        function loadTransferCategories() {
            const fromSelect = document.getElementById('transferFromCategory');
            const toSelect = document.getElementById('transferToCategory');
            
            // 清空现有选项
            fromSelect.innerHTML = '<option value="">请选择源分类</option>';
            toSelect.innerHTML = '<option value="">请选择目标分类</option>';
            
            // 添加分类选项
            Object.entries(categories).forEach(([key, category]) => {
                const option1 = document.createElement('option');
                option1.value = key;
                option1.textContent = `${category.icon} ${category.name}`;
                fromSelect.appendChild(option1);
                
                const option2 = document.createElement('option');
                option2.value = key;
                option2.textContent = `${category.icon} ${category.name}`;
                toSelect.appendChild(option2);
            });
        }
        
        // 确认预算转移
        function confirmTransfer() {
            const fromCategory = document.getElementById('transferFromCategory').value;
            const toCategory = document.getElementById('transferToCategory').value;
            const amount = parseFloat(document.getElementById('transferAmount').value);
            const reason = document.getElementById('transferReason').value;
            
            if (!fromCategory || !toCategory || !amount) {
                showAlert('请填写完整的转移信息');
                return;
            }
            
            if (fromCategory === toCategory) {
                showAlert('源分类和目标分类不能相同');
                return;
            }
            
            // 执行转移逻辑
            const transferRecord = {
                from: fromCategory,
                to: toCategory,
                amount: amount,
                reason: reason,
                date: new Date().toISOString(),
                period: currentPeriod
            };
            
            // 保存转移记录
            adjustmentHistory.push(transferRecord);
            localStorage.setItem('adjustmentHistory', JSON.stringify(adjustmentHistory));
            
            // 更新预算数据
            updateBudgetAfterTransfer(fromCategory, toCategory, amount);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('budgetTransferModal'));
            modal.hide();
            
            showAlert(`已成功转移¥${amount}从${categories[fromCategory].name}到${categories[toCategory].name}`);
            updateBudgetDisplay();
        }
        
        // 更新转移后的预算
        function updateBudgetAfterTransfer(fromCategory, toCategory, amount) {
            const yearMonth = formatYearMonth(currentDate);
            let budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
            
            // 更新源分类预算
            const fromBudgetIndex = budgets.findIndex(b => 
                b.yearMonth === yearMonth &&
                b.primaryCategory === fromCategory &&
                b.type === 'primary'
            );
            
            if (fromBudgetIndex !== -1) {
                budgets[fromBudgetIndex].amount -= amount;
            }
            
            // 更新目标分类预算
            const toBudgetIndex = budgets.findIndex(b => 
                b.yearMonth === yearMonth &&
                b.primaryCategory === toCategory &&
                b.type === 'primary'
            );
            
            if (toBudgetIndex !== -1) {
                budgets[toBudgetIndex].amount += amount;
            }
            
            localStorage.setItem('budgets', JSON.stringify(budgets));
        }
        
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateSmartSuggestions();
            updateAnalysisData();
            
            // 加载调整历史
            adjustmentHistory = JSON.parse(localStorage.getItem('adjustmentHistory') || '[]');
        });
        
        // 当前选择的日期
        let currentDate = new Date();
        
        // 格式化日期为 YYYY-MM 格式
        function formatYearMonth(date) {
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        }
        
        // 格式化显示的月份文本
        function formatMonthDisplay(date) {
            return `${date.getFullYear()}年${date.getMonth() + 1}月`;
        }
        
        // 切换月份
        function changeMonth(delta) {
            currentDate.setMonth(currentDate.getMonth() + delta);
            document.getElementById('currentMonth').textContent = formatMonthDisplay(currentDate);
            updateBudgetDisplay();
            updateTotalBudgetDisplay();
        }
        
        // 更新总预算显示
        function updateTotalBudgetDisplay() {
            const yearMonth = formatYearMonth(currentDate);
            const budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
            
            // 获取当前月份的总预算
            const totalBudget = budgets.find(b => 
                b.type === 'total' && 
                b.period === 'monthly' && 
                b.yearMonth === yearMonth
            );
            
            // 模拟获取实际支出（实际应用中需要从真实数据获取）
            const totalAmount = totalBudget ? totalBudget.amount : 5000;
            const used = Math.floor(Math.random() * totalAmount);
            const remaining = totalAmount - used;
            const percentage = (used / totalAmount) * 100;
            
            // 更新进度条和标签
            document.querySelector('.progress-label').innerHTML = `
                <span>已使用：¥${used.toLocaleString()} / ¥${totalAmount.toLocaleString()}</span>
                <span>剩余：¥${remaining.toLocaleString()}</span>
            `;
            
            const progressBar = document.querySelector('.budget-overview .progress-bar');
            progressBar.style.width = `${percentage}%`;
            progressBar.className = `progress-bar ${
                percentage >= 90 ? 'progress-danger' : 
                percentage >= 70 ? 'progress-warning' : 
                'progress-normal'
            }`;
            
            // 更新统计卡片
            const daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
            const today = new Date().getDate();
            const remainingDays = daysInMonth - today;
            
            document.querySelector('.budget-stats').innerHTML = `
                <div class="stat-card">
                    <div class="stat-label">预算使用率</div>
                    <div class="stat-value">${Math.round(percentage)}%</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">日均支出</div>
                    <div class="stat-value">¥${Math.round(used / today).toLocaleString()}</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">剩余天数</div>
                    <div class="stat-value">${remainingDays}天</div>
                </div>
            `;
            
            // 更新趋势图表
            updateBudgetChart(totalAmount, used);
        }
        
        // 更新趋势图表
        function updateBudgetChart(totalAmount, currentUsed) {
            const daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
            const today = new Date().getDate();
            
            // 生成日期标签
            const labels = [];
            for (let i = 1; i <= daysInMonth; i += 5) {
                labels.push(`${i}日`);
            }
            if (labels[labels.length - 1] !== `${daysInMonth}日`) {
                labels.push(`${daysInMonth}日`);
            }
            
            // 生成预算线数据
            const budgetLineData = labels.map((_, index) => 
                (totalAmount / daysInMonth) * (index * 5 || 1)
            );
            
            // 生成实际支出数据
            const usedData = [];
            for (let i = 1; i <= today; i += 5) {
                usedData.push((currentUsed / today) * i);
            }
            
            // 更新图表
            const chart = Chart.getChart('budgetTrendChart');
            chart.data.labels = labels;
            chart.data.datasets[0].data = usedData;
            chart.data.datasets[1].data = budgetLineData;
            chart.update();
        }
        
        // 显示设置预算弹窗
        function showSetBudgetModal(type) {
            const categoryContainer = document.getElementById('categorySelectContainer');
            categoryContainer.style.display = type === 'category' ? 'block' : 'none';
            
            const modal = new bootstrap.Modal(document.getElementById('setBudgetModal'));
            modal.show();
        }
        
        // 分类数据结构
        const categories = {
            food: {
                name: '餐饮',
                icon: '🍔',
                subcategories: {
                    breakfast: { name: '早餐', icon: '🥐' },
                    lunch: { name: '午餐', icon: '🍚' },
                    dinner: { name: '晚餐', icon: '🍖' },
                    snacks: { name: '零食', icon: '🍪' }
                }
            },
            transport: {
                name: '交通',
                icon: '🚗',
                subcategories: {
                    bus: { name: '公交', icon: '🚌' },
                    subway: { name: '地铁', icon: '🚇' },
                    taxi: { name: '出租车', icon: '🚕' }
                }
            },
            shopping: {
                name: '购物',
                icon: '🛒',
                subcategories: {
                    clothes: { name: '服饰', icon: '👕' },
                    digital: { name: '数码', icon: '📱' },
                    daily: { name: '日用品', icon: '🧴' }
                }
            },
            entertainment: {
                name: '娱乐',
                icon: '🎮',
                subcategories: {
                    movie: { name: '电影', icon: '🎬' },
                    game: { name: '游戏', icon: '🎮' },
                    sports: { name: '运动', icon: '⚽' }
                }
            },
            medical: {
                name: '医疗',
                icon: '💊',
                subcategories: {
                    medicine: { name: '药品', icon: '💊' },
                    treatment: { name: '诊疗', icon: '🏥' }
                }
            }
        };
        
        // 处理分类层级变化
        function handleCategoryLevelChange() {
            const level = document.getElementById('categoryLevel').value;
            const secondaryContainer = document.getElementById('secondaryCategoryContainer');
            
            if (level === 'primary') {
                secondaryContainer.style.display = 'none';
            } else {
                secondaryContainer.style.display = 'block';
                handlePrimaryCategoryChange(); // 更新二级分类选项
            }
        }
        
        // 处理一级分类变化
        function handlePrimaryCategoryChange() {
            const primaryCategory = document.getElementById('primaryCategory').value;
            const secondarySelect = document.getElementById('secondaryCategory');
            const level = document.getElementById('categoryLevel').value;
            
            // 清空现有选项
            secondarySelect.innerHTML = '<option value="">请选择二级分类</option>';
            
            if (level === 'secondary' && primaryCategory && categories[primaryCategory]) {
                const subcategories = categories[primaryCategory].subcategories;
                for (const [key, subcategory] of Object.entries(subcategories)) {
                    const option = document.createElement('option');
                    option.value = key;
                    option.textContent = `${subcategory.icon} ${subcategory.name}`;
                    secondarySelect.appendChild(option);
                }
            }
        }
        
        // 修改保存预算函数
        function saveBudget() {
            const amount = document.getElementById('budgetAmount').value;
            const period = document.getElementById('budgetPeriod').value;
            const warning = document.getElementById('warningCheck').checked;
            const categoryLevel = document.getElementById('categoryLevel')?.value;
            const primaryCategory = document.getElementById('primaryCategory')?.value;
            const secondaryCategory = document.getElementById('secondaryCategory')?.value;
            
            if (!amount || amount <= 0) {
                showAlert('请输入有效的预算金额');
                return;
            }
            
            if (categoryLevel === 'primary' && !primaryCategory) {
                showAlert('请选择一级分类');
                return;
            }
            
            if (categoryLevel === 'secondary' && !secondaryCategory) {
                showAlert('请选择二级分类');
                return;
            }
            
            // 构建预算数据
            const budgetData = {
                amount: parseFloat(amount),
                period,
                warning,
                yearMonth: formatYearMonth(currentDate),
                type: categoryLevel ? categoryLevel : 'total',
                primaryCategory,
                secondaryCategory: categoryLevel === 'secondary' ? secondaryCategory : null,
                createdAt: new Date().toISOString()
            };
            
            // 保存预算数据到本地存储
            let budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
            
            // 如果是更新已有预算，则替换原有数据
            const index = budgets.findIndex(b => 
                b.yearMonth === budgetData.yearMonth &&
                b.type === budgetData.type &&
                b.primaryCategory === budgetData.primaryCategory &&
                b.secondaryCategory === budgetData.secondaryCategory
            );
            
            if (index !== -1) {
                budgets[index] = budgetData;
            } else {
                budgets.push(budgetData);
            }
            
            localStorage.setItem('budgets', JSON.stringify(budgets));
            
            // 更新界面显示
            updateBudgetDisplay();
            updateTotalBudgetDisplay();
            
            const modal = bootstrap.Modal.getInstance(document.getElementById('setBudgetModal'));
            modal.hide();
            
            showAlert('预算设置已保存');
            document.getElementById('budgetForm').reset();
        }
        
        // 修改更新预算显示函数
        function updateBudgetDisplay() {
            const yearMonth = formatYearMonth(currentDate);
            const budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
            const categoriesContainer = document.querySelector('.budget-categories');
            const existingItems = categoriesContainer.querySelectorAll('.category-item');
            
            // 移除现有的分类预算项（保留标题）
            existingItems.forEach(item => item.remove());
            
            // 过滤当前月份的预算数据
            const currentBudgets = budgets.filter(b => 
                b.yearMonth === yearMonth && 
                b.type !== 'total'
            );
            
            // 按分类组织预算数据
            const categoryBudgets = {};
            currentBudgets.forEach(budget => {
                const key = budget.type === 'primary' ? 
                    budget.primaryCategory : 
                    `${budget.primaryCategory}-${budget.secondaryCategory}`;
                categoryBudgets[key] = budget;
            });
            
            // 添加新的预算项
            for (const [key, budget] of Object.entries(categoryBudgets)) {
                const categoryItem = createCategoryBudgetItem(budget);
                categoriesContainer.appendChild(categoryItem);
            }
        }
        
        // 创建分类预算项
        function createCategoryBudgetItem(budget) {
            const item = document.createElement('div');
            item.className = 'category-item expandable';
            
            const primaryCat = categories[budget.primaryCategory];
            const name = budget.type === 'primary' ? 
                `${primaryCat.icon} ${primaryCat.name}` :
                `${primaryCat.subcategories[budget.secondaryCategory].icon} ${primaryCat.subcategories[budget.secondaryCategory].name}`;
            
            // 模拟使用数据（实际应用中需要从真实数据获取）
            const used = Math.floor(Math.random() * budget.amount);
            const percentage = (used / budget.amount) * 100;
            const remaining = budget.amount - used;
            
            let progressClass = 'progress-normal';
            let statusIcon = '✅';
            let statusText = '正常';
            
            if (percentage >= 100) {
                progressClass = 'progress-danger';
                statusIcon = '⚠️';
                statusText = '超支';
            } else if (percentage >= 80) {
                progressClass = 'progress-warning';
                statusIcon = '⚡';
                statusText = '接近限制';
            }
            
            const categoryKey = budget.type === 'primary' ? 
                budget.primaryCategory : 
                `${budget.primaryCategory}-${budget.secondaryCategory}`;
            
            item.innerHTML = `
                <div class="category-header" onclick="toggleCategoryDetails('${categoryKey}')">
                    <div class="category-info">
                        <span class="category-name">${name}</span>
                        <span class="category-status">${statusIcon} ${statusText}</span>
                    </div>
                    <div class="category-amounts">
                        <span class="category-amount">¥${used} / ¥${budget.amount}</span>
                        <span class="expand-icon">▼</span>
                    </div>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar ${progressClass}" style="width: ${Math.min(percentage, 100)}%"></div>
                </div>
                <div class="category-details" id="details-${categoryKey}" style="display: none;">
                    <div class="detail-row">
                        <span>剩余预算:</span>
                        <span class="${remaining >= 0 ? 'text-success' : 'text-danger'}">¥${remaining}</span>
                    </div>
                    <div class="detail-row">
                        <span>预算周期:</span>
                        <span>${budget.period === 'monthly' ? '月度' : budget.period === 'quarterly' ? '季度' : '年度'}</span>
                    </div>
                    <div class="detail-row">
                        <span>平均日支出:</span>
                        <span>¥${(used / new Date().getDate()).toFixed(0)}</span>
                    </div>
                    <div class="detail-actions">
                        <button class="btn-detail" onclick="adjustBudget('${categoryKey}')">调整预算</button>
                        <button class="btn-detail" onclick="viewExpenseHistory('${categoryKey}')">查看明细</button>
                        <button class="btn-detail" onclick="transferBudget('${categoryKey}')">转移预算</button>
                    </div>
                </div>
            `;
            
            return item;
        }
        
        // 切换分类详情显示
        function toggleCategoryDetails(categoryKey) {
            const details = document.getElementById(`details-${categoryKey}`);
            const expandIcon = details.previousElementSibling.previousElementSibling.querySelector('.expand-icon');
            
            if (details.style.display === 'none') {
                details.style.display = 'block';
                expandIcon.textContent = '▲';
                details.style.animation = 'slideDown 0.3s ease-out';
            } else {
                details.style.display = 'none';
                expandIcon.textContent = '▼';
            }
        }
        
        // 调整预算
        function adjustBudget(categoryKey) {
            // 这里可以打开调整预算的模态框
            showAlert('预算调整功能开发中...');
        }
        
        // 查看支出历史
        function viewExpenseHistory(categoryKey) {
            // 这里可以显示该分类的详细支出记录
            showAlert('支出历史查看功能开发中...');
        }
        
        // 转移预算
        function transferBudget(categoryKey) {
            // 预填充转移来源分类
            document.getElementById('transferFromCategory').value = categoryKey.split('-')[0];
            showBudgetTransferModal();
        }
        
        // 应用智能建议
        function applySuggestion() {
            const suggestedAmount = 1800; // 这里应该是动态计算的建议金额
            document.getElementById('budgetAmount').value = suggestedAmount;
            showAlert(`已应用建议金额：¥${suggestedAmount}`);
        }
        
        // 显示支出详情
        function showExpenseDetails() {
            showAlert('正在分析您的餐饮支出详情...');
        }
        
        // 显示节省统计
        function showSavingsStats() {
            showAlert('本月交通费用节省¥120，继续保持！');
        }
        
        // 页面加载时初始化显示
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('currentMonth').addEventListener('click', showMonthPicker);
            document.getElementById('currentMonth').textContent = formatMonthDisplay(currentDate);
            updateBudgetDisplay();
            updateTotalBudgetDisplay();
        });
        
        // 显示提示信息
        function showAlert(message) {
            const alertDiv = document.createElement('div');
            alertDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 9999;
                max-width: 300px;
                text-align: center;
            `;
            alertDiv.textContent = message;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                document.body.removeChild(alertDiv);
            }, 2000);
        }
        
        // 显示月份选择器
        function showMonthPicker() {
            updateMonthGrid();
            const modal = new bootstrap.Modal(document.getElementById('monthPickerModal'));
            modal.show();
        }
        
        // 更新年份显示
        function changeYear(delta) {
            currentDate.setFullYear(currentDate.getFullYear() + delta);
            document.getElementById('yearDisplay').textContent = `${currentDate.getFullYear()}年`;
            updateMonthGrid();
        }
        
        // 更新月份网格
        function updateMonthGrid() {
            const monthGrid = document.getElementById('monthGrid');
            const currentYear = currentDate.getFullYear();
            document.getElementById('yearDisplay').textContent = `${currentYear}年`;
            
            // 清空现有月份
            monthGrid.innerHTML = '';
            
            // 获取当前日期信息
            const today = new Date();
            const currentMonth = currentDate.getMonth();
            
            // 生成月份按钮
            for (let i = 0; i < 12; i++) {
                const monthBtn = document.createElement('button');
                monthBtn.className = 'month-btn';
                if (i === currentMonth) monthBtn.classList.add('selected');
                if (today.getFullYear() === currentYear && today.getMonth() === i) {
                    monthBtn.classList.add('current');
                }
                
                // 获取该月预算信息（示例数据，实际应从存储中获取）
                const yearMonth = `${currentYear}-${String(i + 1).padStart(2, '0')}`;
                const budgets = JSON.parse(localStorage.getItem('budgets') || '[]');
                const monthBudget = budgets.find(b => 
                    b.yearMonth === yearMonth && 
                    b.type === 'total' && 
                    b.period === 'monthly'
                );
                
                monthBtn.innerHTML = `
                    <span class="month-name">${i + 1}月</span>
                    <span class="month-info">${monthBudget ? `预算: ¥${monthBudget.amount.toLocaleString()}` : '未设置'}</span>
                `;
                
                monthBtn.onclick = () => selectMonth(i);
                monthGrid.appendChild(monthBtn);
            }
        }
        
        // 选择月份
        function selectMonth(month) {
            currentDate.setMonth(month);
            document.getElementById('currentMonth').textContent = formatMonthDisplay(currentDate);
            
            // 关闭弹窗
            const modal = bootstrap.Modal.getInstance(document.getElementById('monthPickerModal'));
            modal.hide();
            
            // 更新显示
            updateBudgetDisplay();
            updateTotalBudgetDisplay();
        }
    </script>
</body>
</html>